package com.android.component;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.utils.LogUtil;

import java.util.Iterator;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadPoolTest extends CommonTest {
    private static final String TAG = "ThreadPoolTest";
    ThreadPoolExecutor executor;
    BlockingDeque<Task> tasks = new LinkedBlockingDeque<Task>();

    class Task implements Runnable {
        int id = 0;

        Task(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                LogUtil.d(TAG, "task " + id + " complete");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setButton("开始", onClickListener);
        setButton("停止", onClickListener);

        setButton("call binder function", onClickListener);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == btns[0]) {
                start();
            } else if (v == btns[1]) {
                stop();
            } else if (v == btns[2]) {

            } else if (v == btns[3]) {

            }
        }
    };

    private void stop() {

    }

    private void start() {
        if (executor == null) {
            executor = new ThreadPoolExecutor(3, 20, 0, TimeUnit.MILLISECONDS, null);
            for (int i = 0; i < 100; i++) {
                executor.execute(new Task(i));
            }

            for (int i = 0; i < 100; i += 3) {
                executor.remove(get(i));
            }
        }
    }

    private Runnable get(int i) {
        Iterator<Task> iterator = tasks.iterator();
        while (iterator.hasNext()) {
            Task task = (Task) iterator.next();
            if (task.id == i) {
                return task;
            }
        }
        return null;
    }
}
